package com.panzh.wutao.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ObjectUtil {

    /**
     *
     * @param obj 输入的对象
     * @param clazz 对象的class属性；
     * @return 对象各个参数对应的map; 默认使用hashmap
     */
    public static Map ObjectTranfMap(Object obj, Class clazz) {
        try {
            Field[] fileIds = clazz.getDeclaredFields();
            Map<String,Object> resultMap = new HashMap<>();
            for (Field fd : fileIds) {
                fd.setAccessible(true);
                String attrName = fd.getName();
                Object attrValue = fd.get(obj);
                resultMap.put(attrName,attrValue);
            }
            return resultMap;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Object MapTranfObject(Map map, Class clazz) {
        try {
            Object instance = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                //上帝之手，操控一切；
                field.setAccessible(true);
                String name = field.getName();
                field.set(instance,map.get(name));
            }
            return instance;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
